<?php
/**
 * $Id: other.php 11 2010-11-24 22:10:53Z LEON $
 * $Author: LEON $
 * $LastChangedDate: 2010-11-24 22:10:53 +0000 (Wed, 24 Nov 2010) $
 * $Revision: 11 $
 */
namespace cmFly\utils;
class other {
    public static function randGen($len=32) {
	return substr(md5(uniqid(rand(),1)),0,$len);
    }
    public static function b2i($str,$l=FALSE) {
	if ($l) {$str = strrev($str);}
	$dec = 0;
	$len = strlen($str);
	for($i=0;$i<$len;$i++) {$dec += ord(substr($str,$i,1))*pow(256,$len-$i-1);}
	return $dec;
    }
    public static function hecho($string) {
	return preg_replace('#.#se','sprintf("\\x%02x",ord("$0"))',$string);
    }
    public static function getMicroTime() {
	list($usec, $sec) = explode(" ", microtime());
	return ((float)$usec + (float)$sec);
    }
    public static function getGMT($time=false) {
	if($time==false)
	    $time=time();
	return gmdate("D, d M Y H:i:s", $time)." GMT";
    }
    public static function js_quote($str,$sep='"') {
	return preg_replace("#(\r|\n|".preg_quote($sep,"#").")#","\\$1",$str);
    }
    #Array to JavaScript Array
    public static function toJS(&$arr) {
	if(!is_array($arr))
	    return false;
	$str="{";
	$arr2=Array();
	foreach($arr as $k=>$v) {
	    if(is_array($arr[$k]))
		$arr2[$k]=Utils::toJS($arr[$k]);
	    else
		$arr2[$k]='"'.Utils::js_quote($arr[$k]).'"';
	    $str.='"'.$k.'":'.$arr2[$k].',';
	}
	return $str."'length':".count($arr)."}";
    }
    public static function bytes($a) {
	$unim = array("байт","килобайт","мегабайт","гигабайт","террабайт","PB");
	$c = 0;
	while ($a>=1024) {
	    $c++;
	    $a = $a/1024;
	}
	return number_format($a,($c ? 2 : 0),",",".")." ".$unim[$c];
    }
    public static function isPost() {
	return $_SERVER['REQUEST_METHOD']=="POST";
    }
    public static function convert_x_charset($string,$new_charset,$allowed_charset=array('utf-8', 'windows-1251')) {
	$result=NULL;
	foreach ($allowed_charset as $encoding) {
	    $sample = iconv($encoding, $encoding, $string);
	    if (md5($sample) == md5($string)) {
		$result=$encoding;
		break;
	    }
	}
	if(!$result) {
	    return NULL;
	}
	return iconv($result, $new_charset, $string);
    }
}
?>